package com.tanhua.dubbo.api;

import cn.hutool.core.util.PageUtil;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Video video) {
        mongoTemplate.save(video);
    }

    //查询所有
    public List<Video> findAll(Integer page, Integer pagesize) {
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Video.class);
    }

    //根据id列表查询
    public List<Video> findByIds(String[] ids, Integer page, Integer pagesize) {
        if((page-1) * pagesize < ids.length) {
            Criteria criteria = Criteria.where("id").in(ids);
            Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")))
                    .skip((page - 1) * pagesize)
                    .limit(pagesize);
            return mongoTemplate.find(query,Video.class);
        }else {
            //redis中的数据不足，查询mongodb
            //计算查询的页码  （查询的页码  -  redis中的总页数）
            int totalPage = PageUtil.totalPage(ids.length, pagesize);//总数，每页条数
            page = page - totalPage;
            return findAll(page, pagesize);
        }
    }

    @Override
    public PageResult findAll(Integer page, Integer pagesize, Long userId) {
        //1、创建Criteria对象
        Criteria criteria = Criteria.where("userId").is(userId);
        //2、创建Query对象，设置查询条件
        Query query = Query.query(criteria);
        //3、查询总数
        long count = mongoTemplate.count(query, Video.class);
        //4、向Query中设置分页参数
        query.with(Sort.by(Sort.Order.desc("created")))
            .limit(pagesize)
            .skip((page-1) * pagesize);
        //5、查询列表
        List<Video> list = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,list);
    }
}
